<template>
  <div class="exam-testing-container">
    <!-- 顶部信息区域 -->
    <div class="header-section">
      <div class="header-content">
        <div class="exam-info">
          <el-button type="text" @click="confirmExit" class="back-btn">
            <i class="el-icon-arrow-left"></i>
            退出测试
          </el-button>

          <div class="test-info">
            <span class="test-title">{{ examTitle }}</span>
            <span class="test-type">{{ examType === 'random' ? '随机测试' : '试卷测试' }}</span>
          </div>

          <!-- 计时器 -->
          <div class="timer-section" v-if="examDuration > 0">
            <div class="timer-display" :class="{ 'warning': remainingTime <= 300 }">
              <i class="el-icon-time"></i>
              <span>{{ formatTime(remainingTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 进度条 -->
        <div class="progress-section">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
          </div>
          <span class="progress-text">{{ currentQuestionIndex + 1 }}/{{ questions.length }}</span>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-loading 
          v-loading="loading" 
          element-loading-text="正在加载测试题目..." 
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)" 
        />
      </div>

      <!-- 题目显示区域 -->
      <div v-else-if="questions.length > 0" class="question-section">
        <!-- 题目头部信息 -->
        <div class="question-header">
          <div class="question-number">
            第 {{ currentQuestionIndex + 1 }} 题
           
          </div>
          <div class="question-meta">
            <span class="question-type">{{ getQuestionTypeDisplay(currentQuestion.question_type) }}</span>
            <span class="difficulty-tag" :class="getDifficultyClass(currentQuestion.difficulty)">
              {{ getDifficultyText(currentQuestion.difficulty) }}
            </span>
            <span class="subject-info">{{ getSubjectName(currentQuestion.subject) }}</span>
          </div>
        </div>

        <!-- 题目内容 -->
        <div class="question-content">
          <div class="question-text" v-html="currentQuestion.content"></div>

          <!-- 选择题选项 -->
          <div class="options-container">
            <div 
              v-for="(option, optionKey) in currentQuestion.options" 
              :key="optionKey"
              :class="['option-item', { 'selected': selectedAnswers[currentQuestionIndex] === optionKey }]" 
              @click="selectOptionAndNext(optionKey)"
            >
              <div class="option-label">{{ optionKey }}</div>
              <div class="option-content">{{ option }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="暂无测试题目">
          <el-button type="primary" @click="loadQuestions">重新加载</el-button>
        </el-empty>
      </div>

      <!-- 右侧答题卡 -->
      <div v-if="questions.length > 0" class="answer-card">
        <div class="card-header">
          <h4>答题卡</h4>
          <p class="card-subtitle">已答 {{ answeredCount }}/{{ questions.length }}</p>
        </div>

        <div class="answer-grid">
          <div 
            v-for="(answer, index) in selectedAnswers" 
            :key="index" 
            :class="['answer-cell', getAnswerCellClass(index)]"
            @click="jumpToQuestion(index)"
          >
            {{ index + 1 }}
          </div>
        </div>

        <!-- 答题统计 -->
        <div class="answer-stats">
          <div class="stat-item">
            <span class="stat-label">已答题</span>
            <span class="stat-value answered">{{ answeredCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">未答题</span>
            <span class="stat-value unanswered">{{ questions.length - answeredCount }}</span>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-section">
          <el-button 
            type="primary" 
            size="large" 
            @click="confirmSubmit"
            class="submit-btn"
            :disabled="answeredCount === 0"
          >
            提交测试
          </el-button>
          
        </div>
        
      </div>
    </div>

    <!-- 底部导航区域 -->
    <div class="footer-section">
      <div class="footer-content">
        <div class="navigation-buttons">
          <el-button 
            @click="previousQuestion" 
            :disabled="currentQuestionIndex === 0"
            size="large"
          >
            <i class="el-icon-arrow-left"></i>
            上一题
          </el-button>
          
          <el-button 
            @click="nextQuestion" 
            :disabled="currentQuestionIndex === questions.length - 1"
            size="large"
          >
            下一题
            <i class="el-icon-arrow-right"></i>
          </el-button>
        </div>

        <div class="question-actions">
          <el-button @click="clearCurrentAnswer" v-if="selectedAnswers[currentQuestionIndex]">
            清除答案
          </el-button>
          <el-button @click="markQuestion" :type="markedQuestions.includes(currentQuestionIndex) ? 'warning' : 'default'">
            {{ markedQuestions.includes(currentQuestionIndex) ? '已标记' : '标记题目' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 确认提交对话框 -->
    <el-dialog v-model="showSubmitDialog" title="确认提交" width="40%" :show-close="false">
      <div class="submit-confirmation">
        <div class="confirmation-content">
          <i class="el-icon-warning-outline warning-icon"></i>
          <h3>确认提交测试？</h3>
          <div class="submit-stats">
            <p>总题数：{{ questions.length }}</p>
            <p>已答题：{{ answeredCount }}</p>
            <p>未答题：{{ questions.length - answeredCount }}</p>
            <p v-if="questions.length - answeredCount > 0" class="warning-text">
              还有 {{ questions.length - answeredCount }} 题未作答，提交后将无法修改！
            </p>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showSubmitDialog = false">继续答题</el-button>
          <el-button type="primary" @click="submitExam" :loading="submitting">
            确认提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 确认退出对话框 -->
    <el-dialog v-model="showExitDialog" title="确认退出" width="30%">
      <div class="exit-confirmation">
        <p>确定要退出测试吗？当前进度将不会保存。</p>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showExitDialog = false">继续测试</el-button>
          <el-button type="danger" @click="exitExam">确认退出</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'

export default {
  name: 'ExamPageTesting',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()

    // 响应式数据
    const questions = ref([])
    const currentQuestionIndex = ref(0)
    const selectedAnswers = ref([])
    const markedQuestions = ref([])
    const loading = ref(false)
    const submitting = ref(false)
    const showSubmitDialog = ref(false)
    const showExitDialog = ref(false)

    // 测试信息
    const examTitle = ref('')
    const examType = ref('random') // 'random' | 'paper'
    const examDuration = ref(0) // 分钟
    const startTime = ref(null)
    const remainingTime = ref(0)
    const timer = ref(null)

    // 测试参数
    const testParams = reactive({
      courseId: null,
      questionCount: 20,
      knowledgePoints: [],
      paperId: null,
      paperName: ''
    })

    // API 调用函数
    const api = {
      
      // 获取试卷题目（修改为正确的接口）
  getPaperQuestions: (paperId) => 
    axios.get(`/paperQuestion/byPaper?paper_id=${paperId}`),
  
  // 获取试卷详情
  getPaperById: (paperId) => 
    axios.get(`/exam-papers/${paperId}`),
      
      // 根据课程ID获取所有题目
      getQuestionsByCourse: (courseId) => axios.get(`/question/by-course?courseId=${courseId}`),
      
      // 根据知识点ID获取题目
      getQuestionsByPointId: (pointId) => axios.get(`/question/getbypid?pointId=${pointId}`),
      
      
      // 获取课程信息
      getCourseInfo: (courseId) => axios.get(`/courses/${courseId}`)
    }

    // 前端随机题目生成函数
    const generateRandomQuestions = (allQuestions, count) => {
      if (allQuestions.length <= count) {
        return allQuestions
      }
      
      // Fisher-Yates 洗牌算法
      const shuffled = [...allQuestions]
      for (let i = shuffled.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
      }
      
      return shuffled.slice(0, count)
    }

    // 计算属性
    const currentQuestion = computed(() => {
      if (questions.value.length === 0) return {}
      const question = questions.value[currentQuestionIndex.value]

      // 解析JSON格式的答案数据
      let parsedAnswer = {}
      try {
        parsedAnswer = typeof question.answer === 'string'
          ? JSON.parse(question.answer)
          : question.answer
      } catch (error) {
        console.error('解析答案JSON失败:', error)
        parsedAnswer = { correct: 'A', options: {} }
      }

      return {
        ...question,
        options: parsedAnswer.options || {},
        correctAnswer: parsedAnswer.correct || 'A'
      }
    })

    const progressPercentage = computed(() => {
      if (questions.value.length === 0) return 0
      return ((currentQuestionIndex.value + 1) / questions.value.length) * 100
    })

    const answeredCount = computed(() => {
      return selectedAnswers.value.filter(answer => answer !== null && answer !== undefined).length
    })

    // 工具函数
    const getSubjectName = (subject) => {
      const subjectMap = {
        'DS': '数据结构',
        'OS': '操作系统',
        'CN': '计算机网络',
        'CS': '计算机组成',
        'DB': '数据库'
      }
      return subjectMap[subject] || subject
    }

    const getQuestionTypeDisplay = (questionType) => {
      const typeMap = {
        'CS01': '单选题',
        'CS02': '多选题',
        'CS03': '填空题',
        'CS04': '简答题'
      }
      return typeMap[questionType] || '选择题'
    }

    const getDifficultyText = (difficulty) => {
      const difficultyMap = {
        1: '基础',
        2: '简单',
        3: '中等',
        4: '困难',
        5: '极难'
      }
      return difficultyMap[difficulty] || '中等'
    }

    const getDifficultyClass = (difficulty) => {
      const classMap = {
        1: 'difficulty-easy',
        2: 'difficulty-simple',
        3: 'difficulty-medium',
        4: 'difficulty-hard',
        5: 'difficulty-extreme'
      }
      return classMap[difficulty] || 'difficulty-medium'
    }

    const getAnswerCellClass = (index) => {
      const classes = []
      if (index === currentQuestionIndex.value) {
        classes.push('current')
      }
      if (selectedAnswers.value[index]) {
        classes.push('answered')
      }
      if (markedQuestions.value.includes(index)) {
        classes.push('marked')
      }
      return classes
    }

    const formatTime = (seconds) => {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = seconds % 60

      if (hours > 0) {
        return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
      } else {
        return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
      }
    }

    // 初始化测试参数
    const initTestParams = () => {
      examType.value = route.query.type || 'random'
      
      if (examType.value === 'random') {
        testParams.courseId = parseInt(route.query.courseId)
        testParams.questionCount = parseInt(route.query.questionCount) || 20
        // 修复知识点解析
        try {
          testParams.knowledgePoints = route.query.knowledgePoints 
            ? JSON.parse(route.query.knowledgePoints) 
            : []
        } catch (error) {
          console.error('解析知识点参数失败:', error)
          testParams.knowledgePoints = []
        }
        examDuration.value = parseInt(route.query.duration) || 0
        examTitle.value = `随机测试 - ${testParams.questionCount}题`
      } else if (examType.value === 'paper') {
        testParams.paperId = parseInt(route.query.paperId)
    testParams.paperName = route.query.paperName || ''
    examTitle.value = testParams.paperName
    // 从查询参数中获取试卷时长（如果有的话）
    if (route.query.timeLimit) {
      examDuration.value = parseInt(route.query.timeLimit)
    }
  }
}

    // 加载题目
    const loadQuestions = async () => {
      try {
        loading.value = true
        let allQuestions = []

        if (examType.value === 'random') {
          // 随机测试 - 根据知识点或课程获取题目
          if (testParams.knowledgePoints && testParams.knowledgePoints.length > 0) {
            // 按指定知识点获取题目
            for (const pointId of testParams.knowledgePoints) {
              try {
                const response = await api.getQuestionsByPointId(pointId)
                const pointQuestions = response.data || []
                allQuestions = allQuestions.concat(pointQuestions)
              } catch (error) {
                console.warn(`获取知识点 ${pointId} 的题目失败:`, error)
              }
            }
          } else {
            // 获取整个课程的所有题目
            const response = await api.getQuestionsByCourse(testParams.courseId)
            allQuestions = response.data || []
          }

          // 前端随机选择题目
          questions.value = generateRandomQuestions(allQuestions, testParams.questionCount)
          
        } else {
          try {
        // 1. 获取试卷基本信息
        const paperResponse = await api.getPaperById(testParams.paperId)
        const paperInfo = paperResponse.data
        
        // 2. 获取试卷题目列表
        const questionsResponse = await api.getPaperQuestions(testParams.paperId)
        const paperQuestions = questionsResponse.data || []
        
        // 3. 根据paperQuestions获取完整的题目信息
        // 假设paperQuestions返回的是包含questionId的数组
        const questionPromises = paperQuestions.map(async (pq) => {
          try {
            // 根据questionId获取完整题目信息
            const response = await axios.get(`/question/get?questionId=${pq.questionId}`)
            return response.data
          } catch (error) {
            console.warn(`获取题目 ${pq.questionId} 失败:`, error)
            return null
          }
        })
        
        const fullQuestions = await Promise.all(questionPromises)
        questions.value = fullQuestions.filter(q => q !== null)
        
        // 4. 设置试卷的时长信息
        if (paperInfo.timeLimit) {
          examDuration.value = paperInfo.timeLimit
        }
        
      } catch (error) {
        console.error('获取试卷题目失败:', error)
        ElMessage.error('获取试卷题目失败')
        return
      }
    }
    
    // 初始化答题状态
    selectedAnswers.value = new Array(questions.value.length).fill(null)
    
    if (questions.value.length === 0) {
      ElMessage.warning('暂无测试题目')
      return
    }

    console.log(`加载了 ${questions.value.length} 道题目`)

    // 启动计时器
    if (examDuration.value > 0) {
      startTimer()
    }

  } catch (error) {
    console.error('加载题目失败:', error)
    ElMessage.error('加载题目失败，请重试')
  } finally {
    loading.value = false
  }
}

    // 计时器相关
    const startTimer = () => {
      startTime.value = Date.now()
      remainingTime.value = examDuration.value * 60 // 转换为秒
      
      timer.value = setInterval(() => {
        remainingTime.value--
        
        if (remainingTime.value <= 0) {
          clearInterval(timer.value)
          ElMessage.warning('测试时间到，自动提交！')
          submitExam()
        }
      }, 1000)
    }

    const stopTimer = () => {
      if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
      }
    }

    // 题目操作
    const selectOption = (optionKey) => {
      selectedAnswers.value[currentQuestionIndex.value] = optionKey
    }

    // 选择选项后自动跳转下一题
    const selectOptionAndNext = (optionKey) => {
      selectedAnswers.value[currentQuestionIndex.value] = optionKey;
      // 自动跳转到下一题（如果不是最后一题）
      if (currentQuestionIndex.value < questions.value.length - 1) {
        currentQuestionIndex.value++;
      }
    }

    const jumpToQuestion = (index) => {
      if (index >= 0 && index < questions.value.length) {
        currentQuestionIndex.value = index
      }
    }

    const previousQuestion = () => {
      if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--
      }
    }

    const nextQuestion = () => {
      if (currentQuestionIndex.value < questions.value.length - 1) {
        currentQuestionIndex.value++
      }
    }

    const clearCurrentAnswer = () => {
      selectedAnswers.value[currentQuestionIndex.value] = null
    }

    const markQuestion = () => {
      const index = currentQuestionIndex.value
      const markedIndex = markedQuestions.value.indexOf(index)
      
      if (markedIndex > -1) {
        markedQuestions.value.splice(markedIndex, 1)
        ElMessage.success('已取消标记')
      } else {
        markedQuestions.value.push(index)
        ElMessage.success('已标记题目')
      }
    }

    const calculateTestResult = () => {
  let correctCount = 0
  let totalScore = 0
  const maxScore = 100
  const questionResults = []
  const wrongQuestions = []

  questions.value.forEach((question, index) => {
    const userAnswer = selectedAnswers.value[index]
    let correctAnswer = 'A'

    try {
      const parsedAnswer = typeof question.answer === 'string'
        ? JSON.parse(question.answer)
        : question.answer
      correctAnswer = parsedAnswer.correct || 'A'
    } catch (error) {
      console.warn(`题目 ${index + 1} 答案解析失败:`, error)
    }

    const isCorrect = userAnswer === correctAnswer
    if (isCorrect) {
      correctCount++
    } else {
      wrongQuestions.push({
        questionId: question.questionId,
        courseId: testParams.courseId,
        pointId: question.pointId
      })
    }

    questionResults.push({
      questionIndex: index,
      questionId: question.questionId,
      questionContent: question.content,
      questionType: question.questionType,
      difficulty: question.difficulty,
      userAnswer: userAnswer,
      correctAnswer: correctAnswer,
      isCorrect: isCorrect,
      options: (() => {
        try {
          const parsed = typeof question.answer === 'string'
            ? JSON.parse(question.answer)
            : question.answer
          return parsed.options || {}
        } catch {
          return {}
        }
      })(),
      explanation: question.explanation || '暂无解析'
    })
  })

  totalScore = questions.value.length > 0 
    ? Math.round((correctCount / questions.value.length) * maxScore)
    : 0

  return {
    totalQuestions: questions.value.length,
    correctCount,
    wrongCount: questions.value.length - correctCount,
    accuracy: questions.value.length > 0 
      ? Math.round((correctCount / questions.value.length) * 100) 
      : 0,
    totalScore,
    maxScore,
    questionResults,
    wrongQuestions // ✅ 添加错题数组
  }
}


    // 提交测试
    const confirmSubmit = () => {
      // 检查是否有未答题目
      const unansweredCount = questions.value.length - answeredCount.value
      if (unansweredCount > 0) {
        ElMessageBox.confirm(
          `您还有 ${unansweredCount} 道题未作答，确定要提交吗？`,
          '提交确认',
          {
            confirmButtonText: '确定提交',
            cancelButtonText: '继续答题',
            type: 'warning',
          }
        ).then(() => {
          showSubmitDialog.value = true
        }).catch(() => {
          // 用户选择继续答题
        })
      } else {
        showSubmitDialog.value = true
      }
    }

    // 修复后的 submitExam 函数
const submitExam = async () => {
  try {
    submitting.value = true
    stopTimer()

    const duration = startTime.value ? Math.floor((Date.now() - startTime.value) / 1000) : 0
    const endTime = Date.now()

    const testResult = calculateTestResult()
    
    // ✅ 修复：在函数开头就获取 courseId
    let currentCourseId = null
    
    if (examType.value === 'paper') {
      // 试卷模式：从试卷信息中获取 courseId
      try {
        const paperResponse = await api.getPaperById(testParams.paperId)
        console.log('试卷信息:', paperResponse.data) // 调试日志
        currentCourseId = paperResponse.data?.courseId || paperResponse.data?.course_id
      } catch (error) {
        console.error('获取试卷信息失败:', error)
        // 如果获取失败，尝试从第一个题目中获取
        if (questions.value.length > 0) {
          currentCourseId = questions.value[0].courseId
        }
      }
    } else {
      // 随机测试模式：直接使用测试参数中的 courseId
      currentCourseId = testParams.courseId
    }

    console.log('最终使用的 courseId:', currentCourseId) // 调试日志

    const resultData = {
      examInfo: {
        examType: examType.value,
        examTitle: examTitle.value,
        courseId: currentCourseId, // ✅ 使用修复后的 courseId
        paperId: testParams.paperId,
        paperName: testParams.paperName,
        duration,
        startTime: startTime.value,
        endTime
      },
      result: testResult,
      userInfo: {
        userId: userStore.userInfo?.userId,
        userName: userStore.userInfo?.userName
      }
    }

    console.log('测试结果:', resultData)

    // 如果是试卷测试，保存考试记录到数据库
    if (examType.value === 'paper' && testParams.paperId) {
      try {
        // 构建考试记录对象
        const examRecord = {
          userId: userStore.userInfo?.userId,
          paperId: testParams.paperId,
          totalScore: testResult.maxScore,
          userScore: testResult.totalScore,
          createTime: new Date().toISOString(),
          duration: duration
        }
        
        console.log('保存考试记录:', examRecord)
        
        // 调用新增的考试记录接口
        const examResponse = await axios.post('http://localhost:8080/userexams/add', examRecord)
        console.log('考试记录保存结果:', examResponse.data)
        
        if (examResponse.data && examResponse.data.code === 200) {
          ElMessage.success('考试记录已保存')
        } else {
          console.warn('考试记录保存失败:', examResponse.data)
        }
      } catch (error) {
        console.error('保存考试记录失败:', error)
        ElMessage.warning('考试记录保存失败，但不影响查看结果')
      }
    }

    // ✅ 提交错题记录 - 使用统一的 courseId
    const wrongQuestions = testResult.wrongQuestions || []
    const now = new Date().toISOString()

    // 批量提交错题记录
    const wrongQuestionPromises = wrongQuestions.map(async (q) => {
      const wrongInfo = {
        userId: userStore.userInfo?.userId,
        questionId: q.questionId,
        courseId: currentCourseId, // ✅ 使用统一的 courseId
        pointId: q.pointId,
        sourceType: 2, // 表示来源是测试
        sourceId: testParams.paperId || 0, // 试卷ID，随机测试时可能为0
        wrongCount: 1,
        lastWrongTime: now,
        isMastered: 0,
        isDeleted: 0
      }

      console.log('提交错题记录:', wrongInfo) // 调试日志

      try {
        const response = await axios.post('/wrongquestions/insert', wrongInfo)
        console.log(`错题记录提交成功 - questionId: ${q.questionId}`)
        return response
      } catch (err) {
        console.warn('插入错题失败:', wrongInfo, err)
        throw err
      }
    })

    // 等待所有错题记录提交完成
    if (wrongQuestionPromises.length > 0) {
      try {
        await Promise.allSettled(wrongQuestionPromises)
        console.log('所有错题记录处理完成')
      } catch (error) {
        console.warn('部分错题记录提交失败:', error)
      }
    }

    ElMessage.success('测试提交成功！')

    router.push({
      name: 'ExamPageAnswer',
      query: {
        resultData: JSON.stringify(resultData)
      }
    })

  } catch (error) {
    console.error('提交测试失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
    showSubmitDialog.value = false
  }
}

    // 退出测试
    const confirmExit = () => {
      showExitDialog.value = true
    }

    const exitExam = () => {
      stopTimer()
      router.push('/home/exam')
    }

    // 生命周期
    onMounted(() => {
      initTestParams()
      loadQuestions()
    })

    onUnmounted(() => {
      stopTimer()
    })

    // 监听路由变化（防止用户刷新页面）
    watch(() => route.path, () => {
      if (!route.path.includes('exam-testing')) {
        stopTimer()
      }
    })

    return {
      // 数据
      questions,
      currentQuestionIndex,
      selectedAnswers,
      markedQuestions,
      loading,
      submitting,
      showSubmitDialog,
      showExitDialog,
      examTitle,
      examType,
      examDuration,
      remainingTime,
      // 计算属性
      currentQuestion,
      progressPercentage,
      answeredCount,
      // 方法
      getSubjectName,
      getQuestionTypeDisplay,
      getDifficultyText,
      getDifficultyClass,
      getAnswerCellClass,
      formatTime,
      loadQuestions,
      calculateTestResult,
      selectOption,
      selectOptionAndNext,
      jumpToQuestion,
      previousQuestion,
      nextQuestion,
      clearCurrentAnswer,
      markQuestion,
      confirmSubmit,
      submitExam,
      confirmExit,
      exitExam
    }
  }
}
</script>

<style scoped>
.exam-testing-container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.header-section {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 1rem 0;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
}

.exam-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.back-btn {
  color: #606266;
  font-size: 14px;
}

.back-btn:hover {
  color: #409eff;
}

.test-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.test-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.test-type {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.timer-section {
  display: flex;
  align-items: center;
}

.timer-display {
  background: #f0f9ff;
  border: 1px solid #409eff;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
  display: flex;
  align-items: center;
  gap: 8px;
}

.timer-display.warning {
  background: #fef0f0;
  border-color: #f56c6c;
  color: #f56c6c;
}

.progress-section {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff, #67c23a);
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

/* 主要内容样式 */
.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
  display: flex;
  gap: 2rem;
  position: relative;
}

.loading-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  z-index: 100;
}

.question-section {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.question-header {
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e4e7ed;
}

.question-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 1rem;
}

.question-meta {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.question-type {
  background: #409eff;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.difficulty-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.difficulty-easy { background: #f0f9ff; color: #409eff; }
.difficulty-simple { background: #f0f9ff; color: #67c23a; }
.difficulty-medium { background: #fff7e6; color: #e6a23c; }
.difficulty-hard { background: #fef0f0; color: #f56c6c; }
.difficulty-extreme { background: #f5f5f5; color: #909399; }

.subject-info {
  color: #909399;
  font-size: 14px;
}

.question-content {
  margin-bottom: 2rem;
}

.question-text {
  font-size: 16px;
  line-height: 1.6;
  color: #303133;
  margin-bottom: 2rem;
}

.options-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.option-item {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  padding: 1rem;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.option-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.option-item.selected {
  border-color: #409eff;
  background: #f0f9ff;
}

.option-label {
  width: 32px;
  height: 32px;
  background: #e4e7ed;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  color: #606266;
  flex-shrink: 0;
}

.option-item.selected .option-label {
  background: #409eff;
  color: white;
}

.option-content {
  flex: 1;
  font-size: 15px;
  line-height: 1.5;
  color: #303133;
}

/* 答题卡样式 */
.answer-card {
  width: 300px;
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: fit-content;
  position: sticky;
  top: 120px;
}

.card-header {
  text-align: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e4e7ed;
}

.card-header h4 {
  font-size: 18px;
  color: #303133;
  margin: 0 0 0.5rem 0;
}

.card-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.answer-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  margin-bottom: 1.5rem;
}

.answer-cell {
  width: 40px;
  height: 40px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.answer-cell:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.answer-cell.current {
  border-color: #409eff;
  background: #409eff;
  color: white;
}

.answer-cell.answered {
  background: #f0f9ff;
  border-color: #409eff;
  color: #409eff;
}

.answer-cell.marked {
  background: #fff7e6;
  border-color: #e6a23c;
  color: #e6a23c;
}

.answer-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1.5rem;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
}

.stat-value.answered {
  color: #67c23a;
}

.stat-value.unanswered {
  color: #909399;
}

.submit-section {
  margin-top: 1.5rem;
}

.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
}

/* 底部导航样式 */
.footer-section {
  background: white;
  border-top: 1px solid #e4e7ed;
  padding: 1rem 0;
  position: sticky;
  bottom: 0;
  z-index: 1000;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.navigation-buttons {
  display: flex;
  gap: 1rem;
}

.navigation-buttons .el-button {
  padding: 12px 24px;
  font-size: 14px;
}

.question-actions {
  display: flex;
  gap: 1rem;
}

.question-actions .el-button {
  padding: 8px 16px;
}

/* 对话框样式 */
.submit-confirmation {
  text-align: center;
  padding: 1rem 0;
}

.confirmation-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.warning-icon {
  font-size: 48px;
  color: #e6a23c;
}

.confirmation-content h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.submit-stats {
  background: #f5f7fa;
  padding: 1rem;
  border-radius: 8px;
  text-align: left;
  width: 100%;
  max-width: 300px;
}

.submit-stats p {
  margin: 0.5rem 0;
  color: #606266;
  font-size: 14px;
}

.warning-text {
  color: #f56c6c !important;
  font-weight: 500;
}

.exit-confirmation {
  text-align: center;
  padding: 1rem 0;
}

.exit-confirmation p {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 1rem;
}

.dialog-footer .el-button {
  padding: 12px 24px;
}

/* 空状态样式 */
.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    flex-direction: column;
    gap: 1rem;
  }

  .answer-card {
    width: 100%;
    position: static;
  }

  .answer-grid {
    grid-template-columns: repeat(8, 1fr);
  }

  .footer-content {
    flex-direction: column;
    gap: 1rem;
  }

  .navigation-buttons,
  .question-actions {
    width: 100%;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .exam-info {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }

  .test-info {
    align-items: flex-start;
  }

  .timer-section {
    justify-content: center;
  }

  .progress-section {
    flex-direction: column;
    gap: 0.5rem;
  }

  .progress-text {
    text-align: center;
  }

  .question-section {
    padding: 1rem;
  }

  .question-meta {
    flex-wrap: wrap;
    gap: 0.5rem;
  }

  .option-item {
    padding: 0.75rem;
    gap: 0.75rem;
  }

  .option-label {
    width: 28px;
    height: 28px;
  }

  .answer-grid {
    grid-template-columns: repeat(6, 1fr);
  }

  .answer-cell {
    width: 36px;
    height: 36px;
    font-size: 12px;
  }

  .navigation-buttons {
    flex-direction: column;
    width: 100%;
  }

  .navigation-buttons .el-button {
    width: 100%;
  }

  .question-actions {
    flex-direction: column;
    width: 100%;
  }

  .question-actions .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .main-content {
    padding: 1rem 0.5rem;
  }
  
  .header-content,
  .footer-content {
    padding: 0 0.5rem;
  }

  .question-number {
    font-size: 20px;
  }

  .question-text {
    font-size: 15px;
  }

  .option-content {
    font-size: 14px;
  }

  .answer-grid {
    grid-template-columns: repeat(5, 1fr);
    gap: 6px;
  }

  .answer-cell {
    width: 32px;
    height: 32px;
  }

  .timer-display {
    padding: 6px 10px;
    font-size: 14px;
  }
}

/* 动画效果 */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.question-section {
  animation: slideIn 0.3s ease-out;
}

.option-item {
  animation: slideIn 0.3s ease-out;
}

.option-item:nth-child(1) { animation-delay: 0.1s; }
.option-item:nth-child(2) { animation-delay: 0.2s; }
.option-item:nth-child(3) { animation-delay: 0.3s; }
.option-item:nth-child(4) { animation-delay: 0.4s; }

/* 打印样式 */
@media print {
  .header-section,
  .footer-section,
  .answer-card {
    display: none;
  }

  .main-content {
    padding: 0;
    max-width: none;
  }

  .question-section {
    box-shadow: none;
    border: 1px solid #e4e7ed;
  }
}
</style>